package com.tongji;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class DataThread extends Thread {
	private Handler mHandler;
	private String mAddress;
	public Boolean mRunning = new Boolean(false);
	public Boolean mProcessing = new Boolean(false);
	
	public DataThread(String address, Handler handler) {
		mAddress = address;
		mHandler = handler;
	}
	
	@Override
	public void start() {
		synchronized(mRunning) {
			mRunning = true;
		}
		super.start();
	}
	
	public void stopThread() {
		synchronized(mRunning) {
			mRunning = false;
		}
	}
	
	private void sendUpdataMessage(byte[] image, int len) {
		Message msg = mHandler.obtainMessage();
		Bundle data = new Bundle();
		data.putString("Commond", "update");
		data.putByteArray("Image", image);
		data.putInt("ImageLength", len);
		msg.setData(data);
		mHandler.sendMessage(msg);
	}

	public void run() {
        try {
    		Socket dataSocket = new Socket(mAddress, 56789);
    		InputStream is = dataSocket.getInputStream();
    		OutputStream os = dataSocket.getOutputStream();
    		
    		byte[] size = new byte[4];
    		// 100kb is enough?
    		byte[] image = new byte[100*1024];
    		
    		while (true) {
        		synchronized(mRunning) {
        			if (mRunning == false) {
        	    		is.close();
        	    		dataSocket.close();
        				break;
        			}
        		}
        		
        		int ret = is.read(size, 0, 4);
        		int bufferRead = 0, imageSize = 0;
        		if (ret != -1) {
        			imageSize = ByteTools.byte2Int(size);
        			bufferRead = 0;
        			while (bufferRead < imageSize) {
        				synchronized(mProcessing) {
        					ret = is.read(image, bufferRead, imageSize - bufferRead);
        				}
        				if (ret == -1)
        					break;
        				bufferRead += ret;
        			}
        			os.write(size);
        			os.flush();
        			sendUpdataMessage(image, imageSize);
        		}
    		}
    	} catch (UnknownHostException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (IOException e) {
    		//Log.e("1", "can not connect to " + mAddress);
    		e.printStackTrace();
    	}
	}
}
